﻿//
// Created by Admin on 2024/12/13.
//

#ifndef PISTACHE_MYCHARCONV_H
#define PISTACHE_MYCHARCONV_H
#include <cstring>
#include <system_error>
#include <type_traits>
#include <limits>

struct from_chars_result {
    const char* ptr;  // 指向解析结束后的第一个未处理字符
    std::errc ec;     // 错误代码
};

template <typename T>
typename std::enable_if<std::is_signed<T>::value>::type
checkSign(const char*& first, bool& isNegative) {
	if (*first == '-') {
		isNegative = true;
		++first;
	}
}

template <typename T>
typename std::enable_if<!std::is_signed<T>::value>::type
checkSign(const char*& first, bool& isNegative) {
	//skip
}

template <typename T>
from_chars_result from_chars(const char* first, const char* last, T& value, int base = 10) {
    static_assert(std::is_integral<T>::value, "T must be an integral type");

    if (first == last) {
        return {first, std::errc::invalid_argument}; // 空字符串
    }

    T result = 0;
    bool isNegative = false;

    // 处理负号（仅适用于有符号整数）
	checkSign<T>(first, isNegative);

    if (first == last) {
        return {first, std::errc::invalid_argument}; // 只有符号，没有数字
    }

    while (first != last) {
        char c = *first++;
        int digit;

        if (c >= '0' && c <= '9') {
            digit = c - '0';
        } else if (c >= 'a' && c <= 'z') {
            digit = c - 'a' + 10;
        } else if (c >= 'A' && c <= 'Z') {
            digit = c - 'A' + 10;
        } else {
            return {first - 1, std::errc::invalid_argument}; // 非法字符
        }

        if (digit >= base) {
            return {first - 1, std::errc::invalid_argument}; // 超出基数范围
        }

        // 检查溢出
        if (result > (std::numeric_limits<T>::max() - digit) / base) {
            return {first - 1, std::errc::result_out_of_range};
        }

        result = result * base + digit;
    }

    if (isNegative) {
        if (result > static_cast<T>(std::numeric_limits<T>::max()) + 1) {
            return {first, std::errc::result_out_of_range}; // 溢出
        }
        value = -result;
    } else {
        value = result;
    }

    return {first, std::errc()}; // 转换成功
}
#endif // PISTACHE_MYCHARCONV_H
